package com.zsx.shopping.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zsx.shopping.common.api.search.dto.SkuEsDto;
import com.zsx.shopping.common.exception.ShoppingException;
import com.zsx.shopping.search.config.ElasticSearchConfig;
import com.zsx.shopping.search.constant.SearchConstant;
import com.zsx.shopping.search.service.SaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SaveServiceImpl implements SaveService {

    @Resource
    private RestHighLevelClient restClient;

    @Override
    public void saveProduct(List<SkuEsDto> skuEsDtos) {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsDto skuEsDTO : skuEsDtos) {
            IndexRequest indexRequest = new IndexRequest(SearchConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsDTO.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsDTO);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse response;
        try {
            response = restClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new ShoppingException("搜索引擎保存商品数据失败");
        }
        List<String> collect = Arrays.stream(response.getItems())
                .map(BulkItemResponse::getId)
                .collect(Collectors.toList());
        log.info("商品上架完成, SKU编号：{}", collect);
    }
}
